package com.zhongxi.guoyuan.application;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.zhongxi.guoyuan.entity.BaseResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.DesTool;
import com.zhongxi.guoyuan.utils.DeviceUtils;
import com.zhongxi.guoyuan.utils.MD5Tool;
import com.zhongxi.guoyuan.utils.NetWorkUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

public class MyApplication extends Application {

	public static MyApplication instance;
	public static int majorversion = 3;//api版本号

	//百度地图
	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListener();

	class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			SharedPreferences sharedPrefrences = instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());// 单位：公里每小时
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				sb.append("\nheight : ");
				sb.append(location.getAltitude());// 单位：米
				sb.append("\ndirection : ");
				sb.append(location.getDirection());// 单位度
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				sb.append("\ndescribe : ");
				sb.append("gps定位成功");
				//保存定位信息
				sharedPrefrences.edit().putString("province",location.getProvince() +"").commit();
				sharedPrefrences.edit().putString("city", location.getCity() + "").commit();
				sharedPrefrences.edit().putString("longitude", location.getLongitude() + "").commit();
				sharedPrefrences.edit().putString("latitude", location.getLatitude() + "").commit();

			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				//运营商信息
				sb.append("\noperationers : ");
				sb.append(location.getOperators());
				sb.append("\ndescribe : ");
				sb.append("网络定位成功");
				//保存定位信息
				sharedPrefrences.edit().putString("province",location.getProvince() +"").commit();
				sharedPrefrences.edit().putString("city", location.getCity() + "").commit();
				sharedPrefrences.edit().putString("longitude", location.getLongitude() + "").commit();
				sharedPrefrences.edit().putString("latitude", location.getLatitude() + "").commit();
			} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
				sb.append("\ndescribe : ");
				sb.append("离线定位成功，离线定位结果也是有效的");
				//保存定位信息
				sharedPrefrences.edit().putString("province",location.getProvince() +"").commit();
				sharedPrefrences.edit().putString("city", location.getCity() + "").commit();
				sharedPrefrences.edit().putString("longitude", location.getLongitude() + "").commit();
				sharedPrefrences.edit().putString("latitude", location.getLatitude() + "").commit();
			} else if (location.getLocType() == BDLocation.TypeServerError) {
				sb.append("\ndescribe : ");
				sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
			} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
				sb.append("\ndescribe : ");
				sb.append("网络不同导致定位失败，请检查网络是否通畅");
			} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
				sb.append("\ndescribe : ");
				sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
			}
			sb.append("\nlocationdescribe : ");
			sb.append(location.getLocationDescribe());// 位置语义化信息
			List<Poi> list = location.getPoiList();// POI数据
			if (list != null) {
				sb.append("\npoilist size = : ");
				sb.append(list.size());
				for (Poi p : list) {
					sb.append("\npoi= : ");
					sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
				}
			}
			Log.i("BaiduLocationApiDem", sb.toString());
		}
	}

	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;

		JPushInterface.setDebugMode(true); 	// 设置开启日志,发布app中的Jpush日志关闭
		JPushInterface.init(this);     		// 初始化 JPush

		UMShareAPI.get(this);

		//微信 wx12342956d1cab4f9, a5ae111de7d9ea137e88a5e02c07c94d
		PlatformConfig.setWeixin("wxa67785ccb81c8f81", "80ef0edd57cd28aed7be970668dc5eba");
		PlatformConfig.setQQZone("101372852", "59afd4c01cb7ff9ecc5f46a0ccd01450");

		mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
		initLocation();
		mLocationClient.registerLocationListener( myListener );    //注册监听函数
		mLocationClient.start();

//		Log.i("base", "多次执行");

		new Thread(new Runnable() {
			@Override
			public void run() {
				getSocket();
			}
		}).start();

	}

	/**
	 * 获取进程名
	 * @param context
	 * @return
     */
	private String getProcessName(Context context) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
		if (runningApps == null) {
			return null;
		}
		for (ActivityManager.RunningAppProcessInfo proInfo : runningApps) {
			if (proInfo.pid == android.os.Process.myPid()) {
				if (proInfo.processName != null) {
					return proInfo.processName;
				}
			}
		}
		return null;
	}

	//初始化百度地图
	private void initLocation(){
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
		option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
		int span=1000;
		option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
		option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
		option.setOpenGps(true);//可选，默认false,设置是否使用gps
		option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
		option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
		option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
		option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
		option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
		option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
		mLocationClient.setLocOption(option);
	}

	private void getSocket() {
		Socket socket = null;
		try{
			InetAddress severAddr = InetAddress.getByName("114.55.100.154");
			//应用Server的IP和端口建立Socket对象
			socket = new Socket(severAddr, 6663);
			//将信息通过这个对象来发送给Server
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new OutputStreamWriter(socket.getOutputStream())),true);
			//把用户输入的内容发送给Server
			if(socket.isConnected()){
				String json = getJsonStr();
				out.println(json);
				out.flush();
			}
			//接收服务器信息
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			//得到服务器信息
			String msg = in.readLine();
			Log.i("msg",msg);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(null!=socket)
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	/**
	 * 获取json字符串
	 */
	private String getJsonStr() throws Exception {
		String jsonresult = "";//定义返回字符串
		try {
			JSONObject obj = new JSONObject();
			JSONObject objData = new JSONObject();
			objData.put("identify", DeviceUtils.getDeviceUUID(this));//设备id
			objData.put("platform","android");
			objData.put("userid", MyApplication.getInstance().getUserId());
			objData.put("phonebrand",android.os.Build.BRAND);//设备品牌
			objData.put("osversion", android.os.Build.VERSION.RELEASE);//设备版本号
			objData.put("majorversion",majorversion);//api版本
			objData.put("minorversion",getVersionCode());//版本号
			objData.put("network", NetWorkUtils.getNetworkState(this));//获取网络类型
			objData.put("provider",DeviceUtils.getSimOperatorName(this));//网络供应商
			objData.put("ip", getLocalIPAddress());//ip地址
			objData.put("province",getProvince());//省
			objData.put("city",getCity());//城市
			String now = Calendar.getInstance().getTimeInMillis()+"";
			String a = MD5Tool.sha1(now);
			String b = MD5Tool.Md5(a);
			String sourceStr = MD5Tool.Md5(MD5Tool.sha1(now));
			obj.put("id",DesTool.split(sourceStr,DeviceUtils.getDeviceUUID(this)));//设备id加密
			obj.put("now",now);
			obj.put("data",objData);
			jsonresult = obj.toString()+"\n\r\n";
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jsonresult;
	}

	public static MyApplication getInstance() {
		return instance;
	}

	public String getLatitude(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("latitude","134.232344");
	}

	public String getLongitude(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("longitude","40.245454");
	}

	/**
	 * 快递列表
	 */
	public String getLogistics(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_APPEND).getString("logistics", "");
	}

	/**
	 * 获取省份
	 * @return
     */
	public String getProvince(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("province", "");
	}

	/**
	 * 判断是否为股东
	 * @return
	 */
	public Boolean isShareHolders(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getBoolean("shareHolder", false);
	}

	/**
	 * 判断是否为权益会员
	 */
	public Boolean isPrivilege(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getBoolean("privilege", false);
	}

	/**
	 * 获取城市
	 * @return
     */
	public String getCity(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("city", "");
	}

	/**
	 * 获取店名
	 * @return
	 */
	public String getShopName(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("shopname", "");
	}

	/**
	 * 获取用户名
	 * @return
	 */
	public String getUserName(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("username", "");
	}

	/**
	 * 获取默认收货人
	 * @return
	 */
	public String getName(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("name", "");
	}

	/**
	 * 获取默认手机号
	 * @return
	 */
	public String getUserPhone(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("userphone", "");
	}

	/**
	 * 获取默认地址
	 * @return
	 */
	public String getAddress(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("address", "");
	}

	/**
	 * 获取注册时间
	 * @return
	 */
	public String getRegisterTime(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("time", "");
	}

	/**
	 * 获取用户头像
	 * @return
	 */
	public String getAvatar(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("avatar", "");
	}


	/**
	 * 获取用户编号
	 * @return
	 */
	public String getNum(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("num", "*");
	}

	/**
	 * @return
	 */
	public String getPay(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("pay", "");
	}

	/**
	 * 总管中心用户登录时效凭证
	 * @return
	 */
	public String getCredentials(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("credentials", "");
	}

	/**
	 * 美容院登录时效凭证
	 * @return
	 */
	public String getBeautifulCredentials(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("beautifulcredentials", "");
	}

	/**
	 * 返银供货商登录时效凭证
	 * @return
	 */
	public String getRewardCoinCredentials(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("rewardcoincredentials", "");
	}

	/**
	 * 银币消费商家登录时效凭证
	 * @return
	 */
	public String getCoinCredentials(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("coincredentials", "");
	}

	/**
	 * 获取用户人民币余额
	 * @return
	 */
	public String getRmb(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("rmb", "0");
	}

	/**
	 * 获取用户银币余额
	 * @return
	 */
	public String getSilver(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("silver", "0");
	}

	/**
	 * 获取用户美币余额
	 * @return
	 */
	public String getInnerCurrency(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("inner", "0");
	}

	/**
	 * 获取用户id
	 * @return
     */
	public String getUserId(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("userid", "");
	}

	/**
	 * 获取校验用的随机8位字符串
	 * @return
	 */
	public String getSk(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("sk", "79563421");
	}

	/**
	 * 获取时间戳
	 * @return
	 */
	public String getNow(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("now", "");
	}

	/**
	 * 获取手机号
	 * @return
	 */
	public String getPhone(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("phone", "");
	}

	/**
	 * 获取msgid
	 * @return
	 */
	public String getMsgid(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("msgid", "");
	}

	/**
	 * @return
	 */
	public String getUseId(){
		return instance.getSharedPreferences(Url.APP_SP, MODE_PRIVATE).getString("useid", "");
	}

	/**
	 * 接口拼接校验码
     * @return
     */
	public String getCheck(boolean isUser) {
		String params = null;
		try {
			String utoken = "";
			String sourcestr = MD5Tool.Md5(MD5Tool.sha1(getNow())+getSk());
			String desid = "";
			if(getUserId()!=null&&!"".equals(getUserId())){
				desid = URLEncoder.encode(DesTool.split(sourcestr, getUserId()), "UTF-8");
				utoken = MD5Tool.Md5(getUserId()+getPhone()+getNow());
			}else{
				utoken = "";
			}
			if(isUser){
				params = "id="+desid+"&now="+getNow()+"&utoken="+utoken+"&sk="+getSk()+"&params="+ URLEncoder.encode(DesTool.split(sourcestr, "userid="+getUserId()
						+"&clientvar="+getVersionCode()+"&card="+getImei()+"&silver_console="+MyApplication.getInstance().getCoinCredentials()
						+"&boss_console="+MyApplication.getInstance().getCredentials()+"&inner_console="+MyApplication.getInstance().getBeautifulCredentials()
						+"&welfare_console="+MyApplication.getInstance().getRewardCoinCredentials()), "UTF-8");
			}else{
				params = "id="+desid+"&now="+getNow()+"&utoken="+utoken+"&sk="+getSk()+"&params="+ URLEncoder.encode(DesTool.split(sourcestr, "userid="+getUserId()+"&clientvar="+getVersionCode()+"&card="+getImei()), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return params;
	}

	/**
	 * 对字符串des加密，并对加密字符串中特殊字符转义
	 * @param str
	 * @return
     */
	public String descsc(String str){
		String sourcestr = MD5Tool.Md5(MD5Tool.sha1(getNow())+getSk());
		try {
			return URLEncoder.encode(DesTool.split(sourcestr, str),"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 返回当前程序版本号
	 */
	public int getVersionCode() {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = null;
		try {
			packInfo = packageManager.getPackageInfo(getPackageName(),0);
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		int version = packInfo.versionCode;
		return version;
	}

	public String getImei() {
		TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
		String szImei = TelephonyMgr.getDeviceId();
		return szImei;
	}

	public String getVersionName() {
		String versionName = "";
		PackageManager packageManager = getPackageManager();
		PackageInfo packInfo = null;
		try{
			packInfo = packageManager.getPackageInfo(getPackageName(),0);
			versionName = packInfo.versionName;
		}catch (PackageManager.NameNotFoundException e){
			e.printStackTrace();
		}
		return versionName;
	}

	/**
	 * 获取当前ip地址
	 * @return
     */
	@Nullable
	public String getLocalIPAddress() {
		try {
			for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){
                NetworkInterface intf = en.nextElement();
                for(Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if(!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)){
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void setSpValue(BaseResult baseResult){
		try {
			SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
			sharedPrefrences.edit().putString("now", baseResult.getNow()).commit();
			sharedPrefrences.edit().putString("sk", baseResult.getSafestring()).commit();
			Log.i("base",getNow());
			Log.i("base",getSk());
		}catch (Exception e){
//			Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
	}

	/**
	 * 解析后台返回的加密数据
	 * @param securityKey
	 */
	public String parseSecutiryKey(String securityKey) {
		String jsonStr = "";
		try {
			String sourcestr = MD5Tool.Md5(MyApplication.getInstance().getSk()+MyApplication.getInstance().getNow());
			Log.i("base", sourcestr);
			String str = URLDecoder.decode(securityKey, "UTF-8");
			jsonStr = DesTool.splitdecode(sourcestr, str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonStr;
	}
}